import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/event_manager.dart';
import 'package:wch/helper/preferences_helper.dart';
import 'package:wch/helper/user_wrap_helper.dart';
import 'package:wch/native/native.dart';
import 'package:wch/page/set_wifi_success.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import 'dart:convert' as convert;

import '../helper/aio_decode.dart';
import '../helper/aio_encode.dart';
import '../helper/endian_help.dart';
import '../helper/mqtt.dart';
import '../model/ble.dart';
import '../native/net_business.dart';
import '../utils/loading_utils.dart';

class SetPassPage extends StatefulWidget {
  SetPassPage({super.key, required this.bleModel, required this.model});

  final BleModel bleModel;
  UserWrapModel? model;

  @override
  State<SetPassPage> createState() => _SetPassPageState();
}

class _SetPassPageState extends State<SetPassPage> implements EventManagerInterface{
  bool isCheckedPass = false;
  String wifiName = '';
  String wifiPass = '';
  FocusNode node = FocusNode();
  TextEditingController controller = TextEditingController();
  Timer? wifiTimer;
  OverlayEntry? entry;

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: '设置Wi-Fi',
        body: KeyboardDismissOnTap(
          child: Stack(
            children: [
              Container(
                margin: EdgeInsets.all(7.5.w),
                color: themeBGC,
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 7.5.w),
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  width: ScreenUtil().screenWidth - 30.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
                    color: Colors.white,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      VerPadding(37.h),
                      Row(
                        children: [
                          Image.asset(
                            wifiIcon,
                            width: 16.w,
                            height: 16.w,
                          ),
                          HorPadding(12.w),
                          Text(
                            wifiName,
                            style: TextStyle(
                              color: Color(0xFF3E3F42),
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                      VerPadding(14.h),
                      LineWidget(
                          width: ScreenUtil().screenWidth - 60.w, height: 0.5),
                      Container(
                        height: 60.h,
                        child: Row(
                          children: [
                            Image.asset(
                              wifiPassIcon,
                              width: 14.w,
                              height: 17.h,
                            ),
                            HorPadding(12.w),
                            Expanded(
                              child: CupertinoTextField(
                                focusNode: node,
                                controller: controller,
                                placeholder: 'WiFi密码',
                                maxLength: 16,
                                placeholderStyle: TextStyle(
                                  fontSize: 14,
                                  color: Color(0xFFADADAD),
                                ),
                                keyboardType: TextInputType.visiblePassword,
                                obscureText:true,
                                style:
                                    TextStyle(fontSize: 14, color: F1TextColor),
                                decoration: const BoxDecoration(
                                    color: Colors.transparent),
                              ),
                            ),
                          ],
                        ),
                      ),
                      LineWidget(
                          width: ScreenUtil().screenWidth - 60.w, height: 0.5),
                      VerPadding(20.h),
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            isCheckedPass = !isCheckedPass;
                          });
                        },
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Image.asset(
                              isCheckedPass
                                  ? commonChekcedIcon
                                  : commonUnCheckIcon,
                              width: 15.w,
                              height: 15.w,
                            ),
                            HorPadding(12.w),
                            F14TitleText('记住WiFi密码', color: F2TextColor),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Positioned(
                left: 0,
                right: 0,
                top: ScreenUtil().screenHeight - ScreenUtil().statusBarHeight - 150.h,
                height: 41.h,
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 30.w),
                  child: CommonBtn(
                    title: '连接',
                    callback: (){
                      // NavigatorUtil.push(context, SetWifiSuccessPage());
                      if (controller.text.isEmpty) {
                        ToastUtils.showToast(msg: '请输入WiFi密码');
                        return;
                      }
                      if (controller.text.length < 8) {
                        ToastUtils.showToast(msg: '请至少输入8位WiFi密码');
                        return;
                      }
                      if (wifiName == null) {
                        ToastUtils.showToast(msg: '获取wifi失败，请稍后再试');
                        return;
                      }
                      if (controller.text == null) {
                        ToastUtils.showToast(msg: '请输入密码');
                        return;
                      }
                      LogUtils.log('wifiname=$wifiName');
                      LogUtils.log('wifipass=${controller.text}');
                      List<int> wifiList = EndianUtils.getBytesFixLen(wifiName, EndianUtils.utf8Coding, 64);
                      List<int> passList = EndianUtils.getBytesFixLen(controller.text, EndianUtils.utf8Coding, 20);
                      List<int> cmdList = AIOEncode.setWifiInfo(wifi: wifiList, pass: passList);
                      Loading.getIns().loading(msg: '正在配网中');
                      NativeUtils.nativeAIOListener(cmdList);
                      wifiTimer = Timer.periodic(const Duration(seconds: 20), (timer) {
                        timer.cancel();
                        Loading.getIns().hide();
                        // ToastUtils.showToast(msg: '配网失败，请稍后再试');
                        // NavigatorUtil.pop(context);
                        entry = OverlayEntry(builder: (ctx){
                          return CommonAlert(title: '连网失败', msg: '连接网络失败，请检查Wi-Fi信息并重新尝试', callback: (id){

                          }, entry: entry!, isSingleBtn: true, leftBtnText: '我知道了',);
                        });
                        Overlay.of(context).insert(entry!);
                      });
                    },
                  ),
                ),
              )
            ],
          ),
        ));
  }

  @override
  void initState() {
    EventManager.getIns().addObserver(this);
    NativeUtils.getWifiName();
    node.requestFocus();
  }

  @override
  void dispose() {
    super.dispose();
    EventManager.getIns().removeObserver(this);
    wifiTimer?.cancel();
  }

  @override
  void notify(String methodName, Map data) {
    // TODO: implement notify
    if (methodName == getEventWifi) {
      setState(() {
        wifiName = data['wifiName'];
        String? pass = PreferencesHelper.getWifiPass(wifiName);
        controller.text = pass ?? '';
        isCheckedPass = controller.text.isNotEmpty;
      });
    }  else if (methodName == eventBluetooth) {
      String deviceName = data['deviceName'];
      List<int> cmdList = data['cmd'];
      DecodeEntity decodeEntity = AIODecode.decodeData(cmdList);
      if (decodeEntity.name == 'setWifi') {
        if (decodeEntity.result) {
          ///设置 wifi 成功
          LogUtils.log('设置wifi成功');
          wifiTimer?.cancel();
          Loading.getIns().hide();
          ToastUtils.showToast(msg: '连接wifi成功');

          PreferencesHelper.setWifiAndPass(wifiName, isCheckedPass ? controller.text : '');
          if (widget.model != null) {
            NetBusiness().deliveryDevice(widget.bleModel!.deviceId, widget.model!.userId!, widget.bleModel.deviceName).then((value){
              if (value) {
                // ToastUtils.showToast(msg: '分配设备成功');
                Timer(Duration(seconds: 1), (){
                  String publicTopic = 'RL/SAAS/${widget.bleModel!.deviceName}/APP';
                  Map<String, dynamic> msg = {};
                  msg['messageType'] = 'bindSickPerson';
                  msg['data'] = {
                    'token':PreferencesHelper.getUserToken(),
                    'sickPersonId':widget.model!.userId
                  };
                  mqttPublicMsg(publicTopic, convert.jsonEncode(msg));
                });

                NativeUtils.disconnectAIO();
                // NavigatorUtil.pop(context);
                ///跳转到设置 wifi 界面
                NavigatorUtil.replace(context, SetWifiSuccessPage());

              } else {
                ToastUtils.showToast(msg: '分配设备失败，请稍后再试');
              }
            });
          } else {
            NavigatorUtil.replace(context, SetWifiSuccessPage());
          }
        } else {
          Loading.getIns().hide();
          wifiTimer?.cancel();
          entry = OverlayEntry(builder: (ctx){
            return CommonAlert(title: '连网失败', msg: '连接网络失败，请检查Wi-Fi信息并重新尝试', callback: (id){

            }, entry: entry!, isSingleBtn: true, leftBtnText: '我知道了',);
          });
          Overlay.of(context).insert(entry!);
        }

      }
    }
  }
}
